// utils/http.ts
import http from '@ohos.net.http';
import { BusinessError } from '@ohos.base';

// 定义请求配置接口
interface RequestConfig {
  url: string;
  method?: http.RequestMethod;
  data?: object | string;
  params?: object;
  headers?: object;
  timeout?: number;
}

// 定义响应结构
interface ApiResponse<T = any> {
  data: T;
  status: number;
  statusText: string;
  headers: object;
}

// 定义拦截器类型
type RequestInterceptor = (config: RequestConfig) => RequestConfig | Promise<RequestConfig>;
type ResponseInterceptor = (response: ApiResponse) => ApiResponse | Promise<ApiResponse>;

class HttpClient {
  private requestInterceptors: RequestInterceptor[] = [];
  private responseInterceptors: ResponseInterceptor[] = [];

  constructor() {
    // No need to create instance here, we'll create it per request
  }

  // 添加请求拦截器
  useRequestInterceptor(interceptor: RequestInterceptor): void {
    this.requestInterceptors.push(interceptor);
  }

  // 添加响应拦截器
  useResponseInterceptor(interceptor: ResponseInterceptor): void {
    this.responseInterceptors.push(interceptor);
  }

  private async runRequestInterceptors(config: RequestConfig): Promise<RequestConfig> {
    let currentConfig = config;
    for (const interceptor of this.requestInterceptors) {
      currentConfig = await interceptor(currentConfig);
    }
    return currentConfig;
  }

  private async runResponseInterceptors(response: ApiResponse): Promise<ApiResponse> {
    let currentResponse = response;
    for (const interceptor of this.responseInterceptors) {
      currentResponse = await interceptor(currentResponse);
    }
    return currentResponse;
  }

  async request<T = any>(config: RequestConfig): Promise<ApiResponse<T>> {
    let httpRequest: http.HttpRequest | null = null;
    try {
      const processedConfig = await this.runRequestInterceptors(config);

      // 构建请求URL
      let url = processedConfig.url;
      if (processedConfig.params) {
        const paramsArray: string[] = [];
        Object.entries(processedConfig.params).forEach(([key, value]) => {
          if (value !== undefined && value !== null) {
            paramsArray.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
          }
        });
        if (paramsArray.length > 0) {
          url += `?${paramsArray.join('&')}`;
        }
      }

      httpRequest = http.createHttp();
      const httpResponse = await httpRequest.request(
        url,
        {
          method: processedConfig.method || http.RequestMethod.GET,
          header: processedConfig.headers,
          extraData: processedConfig.method === http.RequestMethod.POST || processedConfig.method === http.RequestMethod.PUT
            ? JSON.stringify(processedConfig.data)
            : undefined,
          connectTimeout: processedConfig.timeout || 60000
        }
      );

      // 转换响应格式 - 使用正确的属性
      const apiResponse: ApiResponse = {
        data: httpResponse.result ? JSON.parse(httpResponse.result as string) : {},
        status: httpResponse.responseCode,
        statusText: httpResponse.responseCode.toString(), // 使用responseCode作为statusText
        headers: httpResponse.header || {}
      };

      return await this.runResponseInterceptors(apiResponse);
    } catch (error) {
      const err = error as BusinessError;
      console.error(`HTTP Request Error: ${err.code} - ${err.message}`);
      throw {
        data: null,
        status: err.code || 500,
        statusText: err.message || 'Unknown Error',
        headers: {}
      };
    } finally {
      httpRequest?.destroy();
    }
  }

  // 快捷方法保持不变
  get<T = any>(url: string, params?: object, config?: Omit<RequestConfig, 'url' | 'method' | 'params'>): Promise<ApiResponse<T>> {
    return this.request<T>({
      url,
      method: http.RequestMethod.GET,
      params,
      ...config
    });
  }

  post<T = any>(url: string, data?: object, config?: Omit<RequestConfig, 'url' | 'method' | 'data'>): Promise<ApiResponse<T>> {
    return this.request<T>({
      url,
      method: http.RequestMethod.POST,
      data,
      ...config
    });
  }

  put<T = any>(url: string, data?: object, config?: Omit<RequestConfig, 'url' | 'method' | 'data'>): Promise<ApiResponse<T>> {
    return this.request<T>({
      url,
      method: http.RequestMethod.PUT,
      data,
      ...config
    });
  }

  delete<T = any>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<ApiResponse<T>> {
    return this.request<T>({
      url,
      method: http.RequestMethod.DELETE,
      ...config
    });
  }
}

// 创建全局实例
const httpClient = new HttpClient();

// 示例：添加请求拦截器（添加token）
httpClient.useRequestInterceptor((config) => {
  // 需要先导入AppStorage
  // import { AppStorage } from '@ohos.application.Storage';
  const token = ''; // 这里应该是获取token的逻辑
  if (token) {
    config.headers = {
      ...config.headers,
      'Authorization': `Bearer ${token}`
    };
  }
  return config;
});

// 添加响应拦截器
httpClient.useResponseInterceptor((response) => {
  if (response.status >= 400) {
    console.error(`Request failed with status code ${response.status}`);
  }
  return response;
});

export default httpClient;